﻿using Brilliant_see.Core.AbstractClass;
using Brilliant_see.Core.Interfaces;
using Brilliant_see.Core.structs;
using Brilliant_see.MapSources.Comics;
using Brilliant_see.MapSources.Enumerators;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Brilliant_see.MapSources
{
    public class BaoziMapSource : IMapSource
    {
        public const string Url = "https://cn.baozimh.com";
        public HttpClient HttpClient { get; set; } = new HttpClient();

        public IEnumerator<string> GetPicEnumerator(Chapter chapter)
            => new BaoziPicEnumerator(Url + chapter.Url, HttpClient);

        public async Task<IEnumerator<Comic>> GetSearchEnumeratorAsync(string keyWord)
        {
            var html = ((await HttpClient.GetStringAsync(Url + "/search?q=" + keyWord)) ?? throw new Exception("包子漫画搜索api异常"))
                .Replace("\n", string.Empty).Replace("&amp;", "&");

            var matchs = Regex.Matches(html, """class="comics-card pure-u-1-2 pure-u-sm-1-2 pure-u-md-1-4 pure-u-lg-1-6"><a href="(.+?)" title="(.+?)".+?<amp-img.+?src="(.+?)">.*?<small class="tags">(.*?)</small>""");
            var result = new List<Comic>();

            foreach (Match match in matchs)
            {
                result.Add(new BaoziComic(this, Url + match.Groups[1].Value,
                    match.Groups[2].Value, match.Groups[3].Value, match.Groups[4].Value.Trim()));
            }

            return result.GetEnumerator();
        }

        public override string ToString() => "包子漫画";
    }
}